# -*- coding: utf-8 -*-
from http.server import HTTPServer, SimpleHTTPRequestHandler
import json
from xls import do_write


class Handle(SimpleHTTPRequestHandler):
    def end_headers(self):
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header('Access-Control-Allow-Methods', "POST, GET, OPTIONS")
        self.send_header("Access-Control-Allow-Headers", "DNT,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type")
        super().end_headers()

    def do_OPTIONS(self):
        self.send_response(204)
        self.end_headers()

    def do_GET(self):
        self.send_response(200)
        self.end_headers()

        ret = "xls"
        self.wfile.write(json.dumps(ret).encode('utf-8'))

    def ret_error(self, e):
        ret = {
                "code": 2000,
                "success": False,
                "fail": True,
                "message": "%s" % e,
                }

        self.send_response(500)
        self.end_headers()
        self.wfile.write(json.dumps(ret).encode('utf-8'))

    def do_POST(self):
        if self.path == '/xls/write':
            try:
                len = int(self.headers['Content-Length'])
                arg = self.rfile.read(len).decode('utf-8')

                data = json.loads(arg)

                e = do_write(data)

                if e is None:
                    ret = {
                            "code": 1000,
                            "success": True,
                            "fail": False,
                            }

                    self.send_response(200)
                    self.end_headers()
                    self.wfile.write(json.dumps(ret).encode('utf-8'))
                else:
                    self.ret_error(e)
            except Exception as e:
                self.ret_error(e)
        else:
            self.ret_error("no server")


if __name__ == "__main__":
    ip = ('', 9986)

    app = HTTPServer(ip, Handle)

    print("bind: 9986")

    app.serve_forever()
